import { Injectable, Logger } from '@nestjs/common'
import qiniu from 'qiniu'

@Injectable()
export class UploadService {
    private readonly accessKey = 'dFd-oYAS99pLG3EJL-guF6A1F_Mzs9_0o5sFplot'
    private readonly secretKey = 'DsTYAKtNfKUDp5jHEcNvxvJhP4lt2Fq8O1NucbsS'
    private readonly bucket = 'xiaolin-oss'
    private readonly mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey)
    private readonly config = new qiniu.conf.Config()
    private readonly formUploader = new qiniu.form_up.FormUploader(this.config)
    private readonly putExtra = new qiniu.form_up.PutExtra()

    async uploadFile(localFilePath: string, key: string): Promise<string> {
        const options = {
            scope: this.bucket + ':' + key,
        }
        const putPolicy = new qiniu.rs.PutPolicy(options)
        const uploadToken = putPolicy.uploadToken(this.mac)

        return new Promise((resolve, reject) => {
            this.formUploader.putFile(uploadToken, key, localFilePath, this.putExtra, (respErr, respBody, respInfo) => {
                if (respErr) {
                    reject(respErr)
                }
                if (respInfo.statusCode === 200) {
                    const bucketManager = new qiniu.rs.BucketManager(this.mac, this.config)
                    const bucketDomain = 'rvmepbqbt.bkt.clouddn.com' // 替换为你的存储桶域名
                    const fileKey = respBody.key
                    const deadline = Math.floor(Date.now() / 1000) + 3600 // 生成链接的有效期，这里设置为1小时
                    const privateLink = bucketManager.privateDownloadUrl(bucketDomain, fileKey, deadline)
                    resolve(privateLink.startsWith('http') ? privateLink : `http://${privateLink}`)
                } else {
                    reject(respBody)
                }
            })
        })
    }
}
